package net.chathu.airgw.model.conn 
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.Socket;
	import flash.utils.ByteArray;
	import flash.utils.Endian;
	import net.chathu.airgw.Soul;
	/**
	 * ...
	 * @author ze
	 */
	public class ChatServerConnection implements IChatServerConnection
	{
		
		private var socket:Socket;
		private var host:String;
		private var port:int;
		private var owner:Soul;
		
		public function ChatServerConnection(owner:Soul,host:String, port:int) 
		{
			this.owner = owner;
			this.host = host;
			this.port = port;
			
			/*readBuffer = new ByteArray();
			readBuffer.endian = "littleEndian";*/
			initConnection();
		}
		
		private function initConnection():Boolean
		{
			if (!socket)
			{
				socket = new Socket();
				socket.addEventListener(Event.CLOSE, onSocketClose);
				socket.addEventListener(Event.CONNECT, onSocketConnect);
				socket.addEventListener(IOErrorEvent.IO_ERROR, onSocketIOError);
				socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSocketSecurityError);
				socket.addEventListener(ProgressEvent.SOCKET_DATA, onData);
				socket.connect(host, port);
				
				return true;
			} else {
				return false;
			}
		}
		
		private function disconnect():Boolean
		{
			if (socket)
			{
				if (socket.connected)
				{
					socket.close();
					return true;
				} else {
					return false;
				}
			} else {
				return false;
			}
		}
		

		
		private function onSocketClose(event:Event):void
		{
			trace("CHAT onSocketClose");
			owner.onChatDisconnected();
		}
		
		private function onSocketConnect(event:Event):void
		{
			trace("CHAT onSocketConnect");
		}
		
		private function onSocketIOError(event:Event):void
		{
			trace("CHAT onSocketIOError");
		}
		
		private function onSocketSecurityError(event:Event):void
		{
			trace("onSocketSecurityError");
		}
		
		private function onData(event:Event):void
		{
			//trace("CHAT onChatSever data, len:" + socket.bytesAvailable);
			
			if (socket.bytesAvailable > 0)
			{
				var readbuffer:ByteArray = new ByteArray();
				readbuffer.endian = Endian.LITTLE_ENDIAN;
				
				socket.readBytes(readbuffer, 0, socket.bytesAvailable);
				
				soul.gwConnection.sendChatPacket(readbuffer);
			}
		}
		
		public function sendPacket(data:ByteArray):void
		{
			data.position = 0; //a biztonsag kedveert
			socket.writeBytes(data,0,data.bytesAvailable);
			socket.flush();
		}
		
				
		public function get soul():Soul
		{
			return owner;
		}
		
		public function get connected():Boolean {
			return socket.connected;
		}
	}

}